package com.example.myapplication;

import android.os.AsyncTask;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class WeatherFragment extends Fragment {
    private static final String TAG = "WeatherFragment";

    private EditText etCityInput;
    private Button btnSearchWeather;
    private TextView tvCityName;
    private TextView tvTemperature;
    private TextView tvCondition;
    private TextView tvWindSpeed;
    private TextView tvForecastTodayTips;
    private TextView tvFutureDay1;
    private TextView tvFutureDay2;
    private TextView tvFutureDay3;
    private TextView tvFutureDay4;

    public WeatherFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_weather, container, false);

        etCityInput = view.findViewById(R.id.et_city_input);
        btnSearchWeather = view.findViewById(R.id.btn_search_weather);

        tvCityName = view.findViewById(R.id.tv_city_name);
        tvTemperature = view.findViewById(R.id.tv_temperature);
        tvCondition = view.findViewById(R.id.tv_condition);
        tvWindSpeed = view.findViewById(R.id.tv_wind_speed);
        tvForecastTodayTips = view.findViewById(R.id.tv_forecast_today_tips);

        tvFutureDay1 = view.findViewById(R.id.tv_future_day1);
        tvFutureDay2 = view.findViewById(R.id.tv_future_day2);
        tvFutureDay3 = view.findViewById(R.id.tv_future_day3);
        tvFutureDay4 = view.findViewById(R.id.tv_future_day4);

        btnSearchWeather.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String city = etCityInput.getText().toString().trim();
                if (!city.isEmpty()) {
                    new FetchWeatherTask().execute(city);
                } else {
                    // Optionally, show a toast or message
                    // Toast.makeText(getContext(), "请输入城市名称", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // Initial fetch for Tianjin
        new FetchWeatherTask().execute("天津");

        return view;
    }

    private class FetchWeatherTask extends AsyncTask<String, Void, String> {

        private String currentCityName;

        @Override
        protected String doInBackground(String... params) {
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;
            String weatherJsonStr = null;

            try {
                currentCityName = params[0];
                final String WEATHER_BASE_URL = "https://v.api.aa1.cn/api/api-tianqi-3/index.php";
                final String MSG_PARAM = "msg";
                final String TYPE_PARAM = "type";

                String encodedCityName = URLEncoder.encode(currentCityName, "UTF-8");

                URL url = new URL(WEATHER_BASE_URL + "?" + MSG_PARAM + "=" + encodedCityName + "&" + TYPE_PARAM + "=" + "1");

                Log.d(TAG, "URL: " + url.toString());

                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                InputStreamReader inputStream = new InputStreamReader(urlConnection.getInputStream());
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                    return null;
                }
                reader = new BufferedReader(inputStream);

                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line + "\n");
                }

                if (buffer.length() == 0) {
                    Log.e(TAG, "Empty response from API.");
                    return null;
                }
                weatherJsonStr = buffer.toString();
                Log.d(TAG, "Raw JSON: " + weatherJsonStr);
                return weatherJsonStr;

            } catch (Exception e) {
                Log.e(TAG, "Error fetching weather data: " + e.getMessage(), e);
                return null;
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final Exception e) {
                        Log.e(TAG, "Error closing reader: " + e.getMessage(), e);
                    }
                }
            }
        }

        @Override
        protected void onPostExecute(String jsonStr) {
            if (jsonStr != null) {
                try {
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    if (jsonObject.has("data") && jsonObject.getJSONArray("data").length() > 0) {
                        JSONArray dataArray = jsonObject.getJSONArray("data");

                        JSONObject todayWeather = dataArray.getJSONObject(0);
                        String tempToday = todayWeather.optString("wendu", "N/A");
                        String weatherToday = todayWeather.optString("tianqi", "N/A");
                        String fengduToday = todayWeather.optString("fengdu", "N/A");
                        String pmToday = todayWeather.optString("pm", "N/A");

                        tvCityName.setText(currentCityName);
                        tvTemperature.setText(tempToday + "°C");
                        tvCondition.setText(weatherToday);
                        tvWindSpeed.setText("风速：" + fengduToday);
                        tvForecastTodayTips.setText("空气质量：" + pmToday);

                        TextView[] futureDayTextViews = {tvFutureDay1, tvFutureDay2, tvFutureDay3, tvFutureDay4};
                        for (int i = 0; i < futureDayTextViews.length; i++) {
                            if (i + 1 < dataArray.length()) {
                                JSONObject futureDay = dataArray.getJSONObject(i + 1);
                                String riqi = futureDay.optString("riqi", "N/A");
                                String wendu = futureDay.optString("wendu", "N/A");
                                String tianqi = futureDay.optString("tianqi", "N/A");
                                String fengdu = futureDay.optString("fengdu", "N/A");

                                futureDayTextViews[i].setText(riqi + "：" + wendu + "°C，" + tianqi + "，" + fengdu);
                            } else {
                                futureDayTextViews[i].setText("未来天气：无数据");
                            }
                        }

                    } else {
                        Log.e(TAG, "'data' array is missing or empty in JSON response.");
                        tvCityName.setText("Error");
                        tvTemperature.setText("N/A");
                        tvCondition.setText("Error");
                        tvWindSpeed.setText("N/A");
                        tvForecastTodayTips.setText("Failed to load weather data: No data available.");
                        tvFutureDay1.setText("未来一天：无数据");
                        tvFutureDay2.setText("未来二天：无数据");
                    }
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
